<?php
namespace Home\Controller;
use Lib\Wx\Auth;
use Lib\Wx\WxSdk;
use Think\Log;

class WxController extends HomeController {
    protected $appid;
    protected $appsecrect;
    protected $host;
    protected $show_grade;
    function __construct()
    {
        parent::__construct();
        $this->appid = C('WX_appID');
        $this->appsecrect = C('WX_appsecret');
        $this->host = 'http://wxg.brainnewlife.com';
        //微信分享，级别
        $this->show_grade = 0;
    }
    function wx(){
        $sign = I('get.sign');
        $redirect = $this->host.'/Wx/index?sign='.$sign;
        $wx_auth = new Auth();
        $wx_url = $wx_auth->getCode($redirect);
        if (isset($wx_url))
        {
            Header("HTTP/1.1 303 See Other");
            Header("Location: $wx_url");
            exit;
        }
    }
    public function index(){

        $userObj = M('Users');
        //第一步,获取code 。code存在。根据code获取openid ，code不存在，跳转  wx/index，获取授权，在跳转到 wx/index，根据code获取openid
//        第二步，根据openid，保存登录信息
//        第三步，
        $title = '金博智慧小游戏';
        $des = '金博智慧是亚洲规模最大、技术体系成熟的专业注意力训练机构。使用美国心理学会的成熟训练体系，结合自主研发专利脑电生物反馈设备，致力于解决中国青少年成长中的注意力问题，是中国注意力训练领域领导品牌。';
        $pic = $this->host.'/Public/Game/images/stms/0.gif';
        $code = I('get.code');
        $wx_auth = new Auth();
        $sign = I('get.sign',uniqid());
        Log::write('请求信息'.json_encode($_REQUEST));
        if('' === $code){
            Header("HTTP/1.1 303 See Other");
            Header("Location: ".$this->host."/Wx/wx?sign=".$sign);
            exit;
        }
        $res = $wx_auth->auth($code);

        //根据openid获取用户信息，如果用户不存在，保存用户

        $openid = $res['openid'];
        $nickname = $res['nickname'];
        $sex = $res['sex'];
        $user_data = json_encode($res);

        if(!$openid){
            Header("HTTP/1.1 303 See Other");
            Header("Location: ".$this->host."/Wx/wx?sign=".$sign);
            exit;
        }

        $parent_data = $userObj->where(array('uniqid'=>$sign))->find();

        if($parent_data){
            $parent_id = $parent_data['id'];
            $data['parent_id'] = $parent_id;
            $data['grade'] = ++$parent_data['grade'];
        }else{
            $parent_id = 0;
            $data['parent_id'] = $parent_id;
            $data['grade'] = 1;
        }
        if($parent_data['grade'] > 10){
            Log::write('分享等级大于10，sign为：'.$sign,Log::ERR);
        }
        $uniqid = uniqid();
        if($openid){
            $res = $userObj->where(array('openid'=>$openid))->find();
//        新用户，保存用户信息
            if(!$res){
                $path = '';
                $data['openid'] = $openid;
                $data['uniqid'] = $uniqid;
                $data['nickname'] = $nickname;
                $data['sex'] = $sex;
                $data['user_data'] = $user_data;
                $data['date'] = date('Y-m-d H:i:s');

                if(false !== $userObj->create($data)){
                    $res = $userObj->add();
                    if($res){
                        //保存path
                        if($data['grade'] == 1){
                            $path = ','.$res.',';
                        }else{
                            $parent_path = $userObj->where(array('id'=>$parent_id))->getField('path');
                            $path = $parent_path.$res.',';
                        }

                    }else{
                        Log::write('保存微信用户信息失败：保存数据为'.json_encode($data),Log::ERR);
                    }
                }

                $userObj->where(array('id'=>$res))->save(array('path'=>$path));
            }else{
                $res = $userObj->where(array('openid'=>$openid))->find();
                if(empty($res['nickname']) || $res['user_data'] != $user_data){
                    $data2['nickname'] = $nickname;
                    $data2['sex'] = $sex;
                    $data2['user_data'] = $user_data;
                    $res = $userObj->where(array('openid'=>$openid))->save(array($data2));
                }
                $uniqid = $res['uniqid'];
            }
        }else{
            Header("HTTP/1.1 303 See Other");
            Header("Location: ".$this->host."/Wx/wx?sign=".$sign);
            exit;
        }

        //保存用户登录历史
//        $login_recode_data['user_id'] = $user_id;
//        $login_recode_data['ip'] = get_client_ip();
//        $login_recode_data['source'] = $_SERVER['REQUEST_URI'];
//        $login_recode_data['date'] = date('Y-m-d H:i:s');
//        //判断重复刷新当前网页
//        $login_date = M('LoginRecord')->where(array('user_id'=>$user_id))->order('id desc')->getField('date');
//        if((time()- strtotime($login_date)) > 60*60){
//
//            $res = M('LoginRecord')->add($login_recode_data);
//            if(!$res){
//                Log::write('保存用户登录信息失败'.json_encode($login_recode_data),Log::ERR);
//            }
//        }else{
//            Log::write('用户多次访问了当前时间：'.date('Y-m-d H:i:s',time()).'上次访问时间'.$login_date.'保存数据为：'.json_encode($login_recode_data),Log::NOTICE);
//        }

//        $data['unionid'] = $res['unionid'];


        //保存用户登录信息

        //获取分享链接
        $link = $this->host.'/Wx/index?sign='.$uniqid;

        $wxsdk = new WxSdk($this->appid,$this->appsecrect);
        $signPackage = $wxsdk->GetSignPackage();

        $this->assign('uniqid',$uniqid);
        $this->assign('title',$title);
        $this->assign('dex',$des);
        $this->assign('pic',$pic);
        $this->assign('link',$link);
        $this->assign('sign',$signPackage);
        $this->display();
    }

    /**
     * 保存用户玩时间
     */
    function playTime(){

        $sign = I('post.sign');

        $data['play_time'] = I('post.playTime','','intval');
        $data['game_code'] = 'game1';
        $data['date'] = date('Y-m-d H:i:s',time());

        $data['address'] = I('post.address');
        Log::write('关闭提交数据'.json_encode($data));
        $data['user_id'] = M('Users')->where(array('uniqid'=>$sign))->getField('id');

        $login_date = M('GameRecord')->where(array('user_id'=>$data['user_id']))->order('id desc')->getField('date');
        if((time()- strtotime($login_date)) > 15){
            if(strtotime($login_date) > strtotime(date('Y-m-d',time()) )){
                $res = M('GameRecord')->where(array('user_id'=>$data['user_id']))->order('id desc')->setInc('play_time',$data['play_time']);
            }else{
                $res = M('GameRecord')->add($data);

            }
            if(!$res){
                Log::write('保存用户登录信息失败'.json_encode($data),Log::ERR);
            }
        }else{
            Log::write('用户多次访问了当前时间：'.date('Y-m-d H:i:s',time()).'上次访问时间'.$login_date.'保存数据为：'.json_encode($data),Log::NOTICE);
        }


    }
}